<template>

  <el-form :model="tableData" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
    <el-card class="box-card">
      <span>基本信息</span>
      <div class="text item">
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单号">
              <el-input v-model="tableData.order.orderNumber" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请时间">
              <el-input :value="getDates(tableData.order.addTime)" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="订单状态">
          <el-input v-model="tableData.order.statusString" disabled></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="汽车总数量">
              <el-input v-model="tableData.order.carSumNumber" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="融资经销商">
              <el-input v-model="tableData.order.dealerName" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="采购总金额(元)">
          <el-input :value="tableData.order.purchaseSumMoney| toFixed2" disabled></el-input>
          <span class="convertCurrency">{{tableData.order.purchaseSumMoney|convertCurrency}}</span>

        </el-form-item>
        <el-form-item label="融资总金额(元)">
          <el-input :value="tableData.order.mortgageSumMoney| toFixed2" disabled></el-input>
          <span class="convertCurrency">{{tableData.order.mortgageSumMoney|convertCurrency}}</span>

        </el-form-item>
        <el-form-item label="融资比例(%)">
          <el-input :value="(((tableData.order.mortgageSumMoney)/(tableData.order.purchaseSumMoney)*100-0).toFixed(2)||'')+'%'" disabled></el-input>
        </el-form-item>
        <el-form-item label="资源审核意见">
          <el-input v-model="tableData.order.resourceAuditOpinion" disabled></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="资源审核人">
              <el-input v-model="tableData.order.resourceAuditPeople" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资源审核时间">
              <el-input :value="getDates(tableData.order.resourceAuditTime)" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="风控审核意见">
          <el-input v-model="tableData.order.riskAuditOpinion" disabled></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="风控审核人">
              <el-input v-model="tableData.order.riskAuditPeople" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风控审核时间">
              <el-input :value="getDates(tableData.order.riskAuditTime)" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
  
      </div>
    </el-card>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>车辆信息</span>
      </div>

      <el-collapse v-model="activeNames" v-for='(item,indexs) in tableData.carTypes' :key="indexs">
        <el-collapse-item :title="item.carName" :name="indexs+1">
          <div class="text item">
            <el-form-item label="汽车数量(台)">
              <el-input v-model="item.carCount" disabled></el-input>
            </el-form-item>
            <el-form-item label="指导价(元)">
              <el-input :value="item.carPrice | toFixed2" disabled></el-input>
              <span class="convertCurrency">{{item.carPrice|convertCurrency}}</span>
            </el-form-item>
            <el-form-item label="采购单价(元)">
              <el-input :value="item.carPurchasePrice| toFixed2" disabled></el-input>
              <span class="convertCurrency">{{item.carPurchasePrice|convertCurrency}}</span>
            </el-form-item>
            <el-form-item label="配置">
              <el-input v-model="item.carConfig" type='textarea' disabled></el-input>
            </el-form-item>
            <el-form-item label="采购金额(元)">
              <el-input :value="item.carPurchaseMoney| toFixed2" disabled></el-input>
              <span class="convertCurrency">{{item.carPurchaseMoney|convertCurrency}}</span>
            </el-form-item>
            <el-form-item label="融资金额(元)">
              <el-input :value="item.carMortgageMoney| toFixed2" disabled></el-input>
              <span class="convertCurrency">{{item.carMortgageMoney|convertCurrency}}</span>
            </el-form-item>
            <el-form-item label="采购合同">
              <qiniu :qiniuImage="item.carContractPics" :packJson="packJson2" :id="item.carContractPics.id" :canDelete="false"></qiniu>
            </el-form-item>


            <div v-if='item.mortgageInspectionList.length!==0'>
              <!-- 这里有个条件 数组长度是否为0，决定渲染模式 -->
              <el-container class='storage' v-for='(ChildItem,index) in item.mortgageInspectionList' :key='index'>
                <el-header class='title'>数量{{index+1}}</el-header>
                <el-form-item label="汽车颜色" :prop="storageCode?'carTypes.'+indexs+'.mortgageInspectionList' +'['+ index+']' + '.color':null"
                  :rules="inspect(false,'汽车颜色')">
                  <el-input v-model=" ChildItem.color " :disabled="dialogSendData.isAdd" :maxlength='10'></el-input>
                </el-form-item>
                <el-form-item label="车架号" :prop="storageCode?'carTypes.'+indexs+'.mortgageInspectionList' +'['+ index+']' + '.vin':null"
                  :rules="inspect(false,'车架号')">
                  <el-input v-model="ChildItem.vin" :disabled="dialogSendData.isAdd" :maxlength='17'></el-input>
                </el-form-item>
                <el-form-item label="发动机号" :prop="storageCode?'carTypes.'+indexs+'.mortgageInspectionList' +'['+ index+']' + '.engineNumber':null"
                  :rules="inspect(false,'发动机号')">
                  <el-input v-model="ChildItem.engineNumber" :disabled="dialogSendData.isAdd" :maxlength='30'></el-input>
                </el-form-item>
                <el-form-item label="生产日期" :prop="storageCode?'carTypes.'+indexs+'.mortgageInspectionList' +'['+ index+']' + '.productionDate':null"
                  :rules="inspect(false,'生产日期')">
                  <el-input v-model="ChildItem.productionDate" :disabled="dialogSendData.isAdd" :maxlength='30'></el-input>
                </el-form-item>

                <el-form-item label="验车照片" >
                  <qiniu :qiniuImage="ChildItem.inspectionPics" :packJson="packJson2"  :id="ChildItem.inspectionPics.id" @setQiniu='setQiniu_image($event)' :canDelete="!dialogSendData.isAdd"></qiniu>
                </el-form-item>
                <el-form-item label="* 手续照片">
                  <qiniu :qiniuImage="ChildItem.proceduresPics" :packJson="packJson2" :id="ChildItem.proceduresPics.id" :canDelete="!dialogSendData.isAdd"></qiniu>
                </el-form-item>
              </el-container>
            </div>

            <div>
              <el-container class='storage' v-for='(ChildItem,key) in (item.fragment) ' :key='ChildItem'>
                <el-header class='title'>数量{{key+item.mortgageInspectionList.length+1}}</el-header>
                
                <el-form-item label="汽车颜色" :prop="storageCode?'carTypes.'+indexs+'.fragment' +'['+ key+']' + '.color':null" :rules="inspect(false,'汽车颜色')">
                  <el-input :maxlength='10' v-model='ChildItem.color' :disabled="dialogSendData.isAdd"></el-input>
                </el-form-item>

                <el-form-item label="车架号" :prop="storageCode?'carTypes.'+indexs+'.fragment' +'['+ key+']' + '.vin':null" :rules="inspect(false,'车架号')">
                  <el-input v-model='ChildItem.vin' :disabled="dialogSendData.isAdd" :maxlength='17'></el-input>
                </el-form-item>
                <el-form-item label="发动机号" :prop="storageCode?'carTypes.'+indexs+'.fragment' +'['+ key+']' + '.engineNumber':null" :rules="inspect(false,'发动机号')">
                  <el-input v-model='ChildItem.engineNumber' :disabled="dialogSendData.isAdd" :maxlength='30'></el-input>
                </el-form-item>
                <el-form-item label="生产日期" :prop="storageCode?'carTypes.'+indexs+'.fragment' +'['+ key+']' + '.productionDate':null" :rules="inspect(false,'生产日期')">
                  <el-input v-model='ChildItem.productionDate' :disabled="dialogSendData.isAdd" :maxlength='30'></el-input>
                </el-form-item>
                <el-form-item label="验车照片" prop="opinion">
                  <qiniu :qiniuImage="ChildItem.inspectionPic" :packJson="packJson2" :id="ChildItem.inspectionPic.id" :canDelete="!dialogSendData.isAdd"></qiniu>
                </el-form-item>
                <el-form-item label="手续照片" prop="opinion">
                  <qiniu :qiniuImage="ChildItem.proceduresPic" :packJson="packJson2" :id="ChildItem.proceduresPic.id" :canDelete="!dialogSendData.isAdd"></qiniu>
                </el-form-item>
              </el-container>
            </div>
          </div>
        </el-collapse-item>

      </el-collapse>
    </el-card>
    <el-card class="box-card">
      <el-form-item label="物管部审核意见" prop="opinion">
        <el-input v-model="tableData.opinion" placeholder="必填，100字限制。" :maxlength='100' :disabled="dialogSendData.isAdd"></el-input>
      </el-form-item>
    </el-card>
    <el-form-item class='align'>
      <el-button type="primary" @click="resetForm('ruleForm')">返回</el-button>
      <!-- <el-button type="primary" @click='temporaryStorage($event)' v-if="buttonValue==='添加'">暂存</el-button> -->
      <el-button @click="submitForm('ruleForm')" v-if="!dialogSendData.isAdd">提交</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
  import qiniu from '@/views/qiniu/upload';
  import {
    require,
    prop,
    decimalTwo,
    muchVerification
  } from '@/utils/rules.js' //表单验证规则
  import agentHttp from '@/utils/agentHttp.js'
  import {
    debounce,
    formatTimer,
    qiniuArray,
    timestampToTime
  } from '@/utils/index.js'
  export default {
    data() {
      return {
        tableData: {
          opinion: ''
        },
        rules: {
          opinion: [require("物管部审核意见")],
        },
        activeNames: [], // 汽车选项卡
        packJson2: {
          maxLength: 50, //最大图片数量
          minLength: 5, //最大图片数量
          accept: "", //image/gif,image/jpeg,image/jpg,image/png如果是这些，可以不传此参数
          size: 4, //图片大小  单位兆
        },
        storageCode: true, //  暂存不需要验证        
      };
    },
    methods: {
      submitForm(formName) { //编辑或者添加数据
        this.$refs[formName].validate(valid => {
          if (valid) {
            var params = {
              mortgageOrderExtendId: this.tableData.order.mortgageOrderExtendId,
              mortgageOrderInspections: [],
              propertyInspectionOpinion: this.tableData.opinion
            }
            var arr1 = [];
            var arr2 = [];
            this.tableData.carTypes.map((items, indexs) => { //编辑
              if (this.buttonValue === '编辑') { //编辑
                items.mortgageInspectionList.map((item, index) => {
                  params.mortgageOrderInspections.push({
                    "color": item.color,
                    "engineNumber": item.engineNumber,
                    "id": item.id,
                    "inspectionPic": item.inspectionPics.image_uri.join(",") || null, //验车照片,
                    "mortgageOrderDetailId": item.mortgageOrderDetailId,
                    "proceduresPic": item.proceduresPics.image_uri.join(",") || null, //验车照片,,
                    "productionDate": item.productionDate,
                    "vin": item.vin
                  })
                })
                //12345678901234561

              } else { // 添加
                params.mortgageOrderInspections = [...this.isData(this.tableData)]
                //     if(items.mortgageInspectionList.length!=0){

                //      arr1.push(items.mortgageInspectionList)  

                //     }else {
                //        arr1.push(this.isData(this.tableData) )
                //     }

              }

            })

            // console.dir(params.mortgageOrderInspections)
            //提交数据给后台
            let path = this.buttonValue === '添加' ? "add" : "update"
            let types = this.buttonValue === '添加' ? "postJson" : "putJson"
            agentHttp[types](`adminApi/admin/mortgage_order_inspection/${path}`, params).then((res) => {
              if (res.success) {
                this.$message.success(res.data || "修改成功");
                this.dialogSendData.dialogFormVisible = false;
                this.$emit('Refresh', null);
              }
            })

          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.dialogSendData.dialogFormVisible = false;
      },
      seachData() { //初始化数据
        var params = this.searchForm || {};
        agentHttp.get(`adminApi/admin/mortgage_order_inspection/view/${this.mortgageOrderExtendId}`).then((data) => {
          if (data.success) {
            this.tableData = data.data
            this.tableData.opinion = this.tableData.order.propertyInspectionOpinion
            qiniuArray(this.tableData);

            //动态创建 无汽车详情时的结构
            // debugger
            this.tableData.carTypes.map((item, index) => {

              item.fragment = [];
              for (var i = 0; i < (item.carCount - item.mortgageInspectionList.length); i++) {
                item.fragment.push({ //动态增加汽车暂存的结构
                  color: '',
                  vin: '',
                  engineNumber: '',
                  productionDate: '',
                  inspectionPic: {
                    id: Math.random()*100,
                    image_uri: [],
                  },
                  proceduresPic: {
                    id:  Math.random()*100,
                    image_uri: []
                  },
                  mortgageOrderDetailId: item.mortgageOrderDetailId
                })
              }

            })
            // console.dir(this.tableData.carTypes)
          }
        })
      },
      formatTimers(key, time) {
        return formatTimer(key, time)
      },
      temporaryStorage(e) { // 暂存数据
        const buttonValue = e.currentTarget.innerText ;
        var params = {
          mortgageOrderExtendId: this.tableData.order.mortgageOrderExtendId,
          mortgageOrderInspections: this.isData(this.tableData,buttonValue),
          propertyInspectionOpinion: this.tableData.order.propertyInspectionOpinion
        }
        
            agentHttp.postJson('adminApi/admin/mortgage_order_inspection/save', params).then((res) => {
              if (res.success) {
                this.$message.success(res.data || "修改成功");
                this.tableData = null ;
                this.seachData()
              }
        })
      },
      getDates(date) {
        return timestampToTime(date)
      },
      isData(data,judge) { //判断暂存和添加的数据是否为空
        var arr = []
        data.carTypes.map((items, index) => {
          // debugger
                  switch(judge){
                    case '暂存':
                            items.fragment.map((item, key, data) => {
                                  if ( //判断条件有点变态 ，抽取不为空的数据出来
                                    item.color != "" &&
                                    item.color != "" &&
                                    item.engineNumber != "" &&
                                    item.inspectionPic.image_uri.length != "0" &&
                                    item.proceduresPic.image_uri.length != "0" &&
                                    item.productionDate != "" &&
                                    item.vin != ""
                                  ) { //加给这个数组
                                    arr.push({
                                      "color": item.color,
                                      "engineNumber": item.engineNumber,
                                      id: item.id || 0,
                                      "inspectionPic": item.inspectionPic.image_uri.join(",") || null, //验车照片
                                      "mortgageOrderDetailId": item.mortgageOrderDetailId,
                                      "proceduresPic": item.proceduresPic.image_uri.join(","), // 手续照片
                                      "productionDate": item.productionDate,
                                      "vin": item.vin,
                                      //  
                                    })
                                  }
                                })
                                 items.mortgageInspectionList.map((item,key)=>{
                                arr.push({
                                  "color": item.color,
                                  "engineNumber": item.engineNumber,
                                  id: item.id || 0,
                                  "inspectionPic": item.inspectionPics.image_uri.join(",") || null, //验车照片
                                  "mortgageOrderDetailId": item.mortgageOrderDetailId,
                                  "proceduresPic": item.proceduresPics.image_uri.join(",")|| null, // 手续照片
                                  "productionDate": item.productionDate,
                                  "vin": item.vin, 
                                })
                            
                          })
                            
                          break;
                    default:
                          if(items.mortgageInspectionList.length!=0){
                          items.mortgageInspectionList.map((item,key)=>{
                              arr.push({
                                  "color": item.color,
                                  "engineNumber": item.engineNumber,
                                  id: item.id || 0,
                                  "inspectionPic": item.inspectionPics.image_uri.join(",") || null, //验车照片
                                  "mortgageOrderDetailId": item.mortgageOrderDetailId,
                                  "proceduresPic": item.proceduresPics.image_uri.join(",")|| null, // 手续照片
                                  "productionDate": item.productionDate,
                                  "vin": item.vin, 
                                })
                            
                          })
                          
                          }
                          items.fragment.filter((item, key, data) => {
                                  if ( //判断条件有点变态 ，抽取不为空的数据出来
                                    item.color != "" &&
                                    item.color != "" &&
                                    item.engineNumber != "" &&
                                    item.inspectionPic.image_uri.length != "0" &&
                                    item.proceduresPic.image_uri.length != "0" &&
                                    item.productionDate != "" &&
                                    item.vin != ""

                                  ) { //加给这个数组
                                    arr.push({
                                      "color": item.color,
                                      "engineNumber": item.engineNumber,
                                      id: item.id || 0,
                                      "inspectionPic": item.inspectionPic.image_uri.join(",") || null, //验车照片
                                      "mortgageOrderDetailId": item.mortgageOrderDetailId,
                                      "proceduresPic": item.proceduresPic.image_uri.join(","), // 手续照片
                                      "productionDate": item.productionDate,
                                      "vin": item.vin,
                                      //  
                                    })
                                  }
                                })
                          
                      break;
                  }
        })
        // console.dir(arr);
        return arr
      },
      inspect(code, data) {
        var type = decimalTwo;
        return muchVerification(code, data, type)
      },
      setQiniu_image(a){
        // console.dir(a)
        //通过id找到位置
         data.carTypes.map((items,indexs)=>{
               items.fragment.map((item,index)=>{

               })
         })
      }
    },
    props: {
      dialogSendData: {
        type: Object
      },
      mortgageOrderExtendId: {
        type: Number
      },
      buttonValue: {
        type: String
      }
    },
    mounted() {
      this.seachData()

    },
    components: {
      qiniu
    },
    created() {
      agentHttp.get(`adminApi/admin/mortgage_order_inspection/view/${this.mortgageOrderExtendId}`).then((res => {

      }))
    }
  };

</script>

<style lang="scss" scoped>
  .text {
    font-size: 14px;
  }

  .fragment {
    margin: 20px auto 40px !important;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both;
  }

  .box-card {
    margin-top: 20px;
  }

  .align {
    margin: 50px auto 0;
    text-align: center;
  }

  .title {
    background-color: #B3C0D1;
    color: #333;
    text-align: center;
    line-height: 30px;
    padding: 5px 0 5px 5px;
    display: flex;
    margin-bottom: 10px;
  }

</style>

